<template>
  <div class="products-container">
    <div class="coffee-bg"></div>
    <div class="header-actions">
      <el-button type="primary" @click="handleAdd">
        <i class="el-icon-plus"></i>添加商品
      </el-button>
      <el-input
        v-model="searchQuery"
        placeholder="搜索商品"
        style="width: 200px; margin-left: 16px">
        <template slot="prefix">
          <i class="el-icon-search"></i>
        </template>
      </el-input>
      <el-button type="success" icon="el-icon-download" @click="exportProducts" style="margin-left:16px">导出Excel</el-button>
    </div>

    <el-table :data="filteredProducts" style="width: 100%; margin-top: 20px" class="coffee-table">
      <el-table-column prop="image" label="图片" width="80">
        <template slot-scope="scope">
          <el-image v-if="scope.row.image" :src="scope.row.image" :preview-src-list="[scope.row.image]" style="width:40px;height:40px;object-fit:cover;border-radius:8px;box-shadow:0 2px 8px #b0896822;" />
        </template>
      </el-table-column>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="商品名称" />
      <el-table-column prop="category" label="类别" />
      <el-table-column prop="price" label="价格">
        <template slot-scope="scope">
          ¥{{ scope.row.price.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" />
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === '在售' ? 'success' : 'info'" :class="scope.row.status === '在售' ? 'coffee-tag' : ''">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑商品对话框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === 'add' ? '添加商品' : '编辑商品'"
      width="500px"
      class="coffee-dialog">
      <el-form :model="productForm" :rules="rules" ref="productFormRef" label-width="100px">
        <el-form-item label="商品图片">
          <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :before-upload="beforeImageUpload"
            :on-change="handleImageChange"
            :on-remove="handleImageRemove"
            :file-list="productForm.image ? [{name:'图片',url:productForm.image}] : []"
            accept="image/*"
          >
            <img v-if="productForm.image" :src="productForm.image" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.name" />
        </el-form-item>
        <el-form-item label="类别" prop="category">
          <el-select v-model="productForm.category" placeholder="选择类别">
            <el-option label="咖啡" value="咖啡" />
            <el-option label="茶饮" value="茶饮" />
            <el-option label="甜点" value="甜点" />
            <el-option label="小食" value="小食" />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="productForm.price" :precision="2" :step="0.1" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="productForm.stock" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="productForm.status">
            <el-option label="在售" value="在售" />
            <el-option label="下架" value="下架" />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as XLSX from 'xlsx'

export default {
  data() {
    return {
      searchQuery: '',
      dialogVisible: false,
      dialogType: 'add',
      productForm: {
        image: '',
        name: '',
        category: '',
        price: 0,
        stock: 0,
        status: '在售'
      },
      products: [],
      rules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择类别', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入价格', trigger: 'blur' },
          { type: 'number', min: 0.01, message: '价格必须大于0', trigger: 'blur' }
        ],
        stock: [
          { required: true, message: '请输入库存', trigger: 'blur' },
          { type: 'number', min: 0, message: '库存不能为负', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    filteredProducts() {
      return this.products.filter(product =>
        product.name.toLowerCase().includes(this.searchQuery.toLowerCase())
      )
    }
  },
  created() {
    this.loadProducts()
  },
  methods: {
    loadProducts() {
      const local = localStorage.getItem('products')
      if (local) {
        this.products = JSON.parse(local)
      }
    },
    // 日志写入方法
    addOperationLog(action, detail) {
      const user = JSON.parse(localStorage.getItem('adminUser') || '{}')
      const logs = JSON.parse(localStorage.getItem('operationLogs') || '[]')
      logs.push({
        time: new Date().toLocaleString(),
        user: user.username || '未知',
        action,
        detail
      })
      localStorage.setItem('operationLogs', JSON.stringify(logs))
    },
    handleAdd() {
      this.dialogType = 'add'
      this.productForm = { image: '', name: '', category: '', price: 0, stock: 0, status: '在售' }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogType = 'edit'
      this.productForm = { ...row }
      this.dialogVisible = true
    },
    handleDelete(row) {
      this.$confirm('确定要删除这个商品吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.products = this.products.filter(item => item.id !== row.id)
        localStorage.setItem('products', JSON.stringify(this.products))
        this.$message.success('删除成功')
        this.addOperationLog('删除商品', `商品ID:${row.id} 名称:${row.name}`)
      }).catch(() => {
        // 用户点击取消按钮时，不执行任何操作
      })
    },
    handleSubmit() {
      this.$refs.productFormRef.validate(valid => {
        if (!valid) return
        if (this.dialogType === 'add') {
          const newProduct = { ...this.productForm, id: `PROD${Date.now()}` }
          this.products.push(newProduct)
          localStorage.setItem('products', JSON.stringify(this.products))
          this.$message.success('添加成功')
          this.addOperationLog('新增商品', `商品ID:${newProduct.id} 名称:${newProduct.name}`)
        } else {
          const index = this.products.findIndex(item => item.id === this.productForm.id)
          this.products.splice(index, 1, { ...this.productForm })
          localStorage.setItem('products', JSON.stringify(this.products))
          this.$message.success('更新成功')
          this.addOperationLog('编辑商品', `商品ID:${this.productForm.id} 名称:${this.productForm.name}`)
        }
        this.dialogVisible = false
      })
    },
    beforeImageUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isImage) {
        this.$message.error('只能上传图片文件!')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过2MB!')
      }
      return isImage && isLt2M
    },
    handleImageChange(file) {
      const reader = new FileReader()
      reader.onload = e => {
        this.productForm.image = e.target.result
      }
      reader.readAsDataURL(file.raw)
    },
    handleImageRemove() {
      this.productForm.image = ''
    },
    exportProducts() {
      // 只导出当前筛选后的商品
      const data = this.filteredProducts.map(product => ({
        ID: product.id,
        商品名称: product.name,
        类别: product.category,
        价格: product.price,
        库存: product.stock,
        状态: product.status
      }))
      const ws = XLSX.utils.json_to_sheet(data)
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, '商品')
      XLSX.writeFile(wb, '商品数据.xlsx')
      this.addOperationLog('导出商品', `导出${data.length}条商品`)
    }
  }
}
</script>

<style scoped>
.products-container {
  padding: 20px;
  min-height: 100vh;
  background: linear-gradient(135deg, #e7d2ba 0%, #b08968 100%);
  position: relative;
  overflow: hidden;
}
.coffee-bg {
  position: absolute;
  left: 0; right: 0; top: 0; bottom: 0;
  z-index: 0;
  pointer-events: none;
  background: url('https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/2615.png') repeat 0 0/120px auto;
  opacity: 0.06;
}
.header-actions {
  display: flex;
  align-items: center;
  z-index: 1;
}
.el-button--primary {
  background: linear-gradient(90deg, #a47149 0%, #7c4f22 100%);
  border: none;
  color: #fff;
  font-weight: bold;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(124, 79, 34, 0.08);
  transition: background 0.2s;
}
.el-button--primary:hover {
  background: linear-gradient(90deg, #7c4f22 0%, #a47149 100%);
}
.el-button--success {
  background: linear-gradient(90deg, #b08968 0%, #a47149 100%);
  border: none;
  color: #fff;
  font-weight: bold;
  border-radius: 8px;
}
.el-input__inner {
  background: #f8f5f2;
  border-radius: 8px;
  border: 1px solid #e0c3a0;
}
.coffee-table {
  background: rgba(255,255,255,0.96);
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(124, 79, 34, 0.08);
  overflow: hidden;
}
.coffee-table th, .coffee-table td {
  background: transparent !important;
}
.coffee-tag {
  background: #e7d2ba !important;
  color: #7c4f22 !important;
  border: none !important;
}
.coffee-dialog .el-dialog {
  border-radius: 16px;
  box-shadow: 0 4px 18px 0 rgba(124, 79, 34, 0.10);
  border: 1px solid #e0c3a0;
  background: rgba(255, 255, 255, 0.98);
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #b08968;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  background: #f8f5f2;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #a47149;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}
.avatar {
  width: 80px;
  height: 80px;
  display: block;
  object-fit: cover;
  border-radius: 8px;
  box-shadow: 0 2px 8px #b0896822;
}
</style> 